#include <iostream>
#include <string>
#include <fstream>
#include "Report.h"
#include "ReportSystemExceptions.h"
using namespace std;
string GetExeDirectory(string ExecFullPath);
string ReadTextTemplate(string path);
int main(int argc, char* argv[])
{
	try
	{
		string txtTemplate = ReadTextTemplate(GetExeDirectory(argv[0]) + "files\\template.txt");
		if (txtTemplate == "")
		{
			cout << "Cannot open file with text template. Terminating program." << endl;
			cin.get();
			return -1;
		}
		Report myReport(GetExeDirectory(argv[0]) + "files\\parameters.txt", txtTemplate);
		myReport.GenerateReport();
		cout << "Report template:" << endl
				<< myReport.GetTextTemplate() << endl
				<< "Generated report:" << endl
				<< myReport.GetReport() << endl;

		cout << "PLease, enter the path to save report, including file's name:" << endl;
		string pathToSave;
		getline(cin, pathToSave, '\n');
		if(myReport.SaveReport(pathToSave))
		{
			cout << "Your report was successfully saved in " << pathToSave << endl;
		}
		else
		{
			cout << "There were problems when saving report. Operation is canceled." << endl;
		}
		cout << "Press the \"ENTER\" key to exit the program." << endl;
		cin.get();
		return 0;
	}
	catch(ReportSystemExceptions& excep)
	{
		cout << excep.message << endl;
		if (excep.exitProgramStatus == YES)
		{
			cout << "Fatal error, program is terminating, press the \"ENTER\" key." << endl;
			cin.get();
			exit(-1);
		}
		else
		{
			cout << "Program is going on, press the \"ENTER\" key." << endl;
			cin.get();
		}
	}
	catch(exception& excep)
	{
		cout << "Unexpected error: " << excep.what() << endl
			<< "Do you want to continue (1 - YES, another number - NO)? ";
		int choiceToContinue;
		cin >> choiceToContinue; cin.get();
		if (choiceToContinue != 1)
		{
			exit(-1);
		}
	}
}
//
string ReadTextTemplate(string path)
{
	// Method returns all text from the file with report template
	ifstream fileWithTemplate(path);
	if (! fileWithTemplate)
	{
		return "";
	}
	istreambuf_iterator<char> begin(fileWithTemplate), end;
	string textTemplate(begin, end);
	return textTemplate;
}
string GetExeDirectory(string ExecFullPath)
{
	// Method returns the directory, where *.exe file of current project is located.
	string::size_type pos = string( ExecFullPath ).find_last_of( "\\/" );
	return string( ExecFullPath ).substr( 0, pos) + '\\';
}